package com.apobates.jforum.grief.schema2doc.output.freeMarker;

import com.apobates.jforum.grief.schema2doc.core.SchemaOutput;
import com.apobates.jforum.grief.schema2doc.core.entity.Information;
import com.apobates.jforum.grief.schema2doc.core.entity.Table;
import freemarker.template.TemplateException;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Word文件输出
 * 使用Freemarker
 */
public class FreeMarkerWordOutput implements SchemaOutput, SupportEmbedTemplate {
    private final String outputPath;
    private ExportTemplate template;

    public FreeMarkerWordOutput(String outputPath) {
        this.outputPath = outputPath;
    }

    @Override
    public int flush(Information information, Stream<Table> tables) throws IOException {
        ExportTemplate tempTemplate = Optional.ofNullable(template).orElse(ExportTemplate.basic());

        Map<String, Object> templateData = new HashMap<>();
        templateData.put("tables", tables.collect(Collectors.toList()));
        templateData.put("description", information.getDescription());
        templateData.put("version", information.getVersion());
        templateData.put("database", information.getDatabase());
        templateData.put("title", information.getTitle());
        try {
            String outputFilePath = String.format("%s/%d.docx", outputPath, System.currentTimeMillis());
            try(Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFilePath), "UTF-8"));){
                // 生成文件
                tempTemplate.get().process(templateData, out);
                out.flush();
            }
        }catch (TemplateException e){
            throw new IOException(e);
        }
        return 0;
    }

    @Override
    public SchemaOutput embed(ExportTemplate template) {
        this.template = template;
        return this;
    }
}
